# -*- coding: utf-8 -*-
import json
import logging.config
import threading
import time

from conf.config import BEANSTALKD_HOST, BEANSTALKD_PORT
from conf.logging import LOGGING_DICT_CONFIG
from helper.payment.pay_util import reward_agency_user_register
from lib import beanstalkc
from lib.beanstalkc import DeadlineSoon

logger = logging.getLogger("execute_mq")
logging.config.dictConfig(LOGGING_DICT_CONFIG)
logging.getLogger("requests").setLevel(logging.ERROR)


def start():
    """
    处理延时任务：给发卡人激励

    :return:
    """

    try:
        logger.info("start reward server")
        logger.info("connect to beanstalk")
        bt = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=60)
        bt.watch("reward_agency")
        while True:
            job = bt.reserve(timeout=5)
            if job is None:
                continue
            try:
                logger.debug(job.body)
                body = json.loads(job.body)
                agency_uid = body["agency_uid"]
                # 给发卡人激励
                reward_agency_user_register(agency_uid)
                job.delete()
            except Exception as e:
                logger.exception(e)
                logger.info("jid=%s，state=%s" % (job.jid, job.stats()['state']))
                job.release(delay=60)
    except Exception as e:
        if not isinstance(e, DeadlineSoon):
            logger.exception(e)
        time.sleep(1)
        logger.info("restart ...")
        start()


class RewardAgency(threading.Thread):
    def run(self):
        logger.info("start reward thread!")
        start()


if __name__ == "__main__":
    RewardAgency().run()
